#include<stdio.h>
#include<string.h>                                                              
#include<unistd.h>
#include<pthread.h>
#include<fcntl.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<stdlib.h>
#include<sys/epoll.h>

#define SERVERPORT 8000
#define BUFSIZE 1024 
#define EVENTSIZE 1025

int createsock(int port)
{
    int lfd=socket(AF_INET,SOCK_STREAM,0);
    if(lfd==-1)
    {
        perror("socket error");
        exit(1);
    }
    struct sockaddr_in serveraddr;
    serveraddr.sin_family=AF_INET;
    serveraddr.sin_port=htons(SERVERPORT);
    serveraddr.sin_addr.s_addr=0;//任意ip
    //绑定ip和端口号
    bind(lfd,(struct sockaddr*)&serveraddr,sizeof(serveraddr));
    //主动套接字转被动套接字
    listen(lfd,64);
    return lfd;
}

int main(int argc, char* argv[])
{
    char buf[BUFSIZE];

    int lfd=createsock(SERVERPORT);

    int epfd=epoll_create(64);//创建一个epoll的句柄（对象）
    if(epfd==-1)
    {
        perror("epoll_create error");
        exit(1);
    }
    struct epoll_event events[EVENTSIZE];//创建一个数组，用来存触发事件链表中的文件描述符

    struct epoll_event event;
    event.events=EPOLLIN;
    event.data.fd=lfd;
    epoll_ctl(epfd,EPOLL_CTL_ADD,lfd,&event);//将lfd添加到红黑树中

    while(1)
    {
        int wait_ret=epoll_wait(epfd,events,EVENTSIZE,-1);//等待事件的发生
        if(wait_ret==-1)
        {
            perror("epoll_wait error");
            exit(1);
        }
        for(int i=0;i<wait_ret;i++)
        {
            if(events[i].events & EPOLLIN)//读事件触发
            {
                if(events[i].data.fd==lfd)//存的为lfd
                {
                    int cfd=accept(lfd,NULL,NULL);
                    if(cfd==-1)
                    {
                        perror("accept error");
                        exit(1);
                    }
                    printf("客户端建立连接\n");
                    event.events=EPOLLIN;
                    event.data.fd=cfd;
                    epoll_ctl(epfd,EPOLL_CTL_ADD,cfd,&event);
                }
                else//存的是cfd文件描述符
                {
                    int read_ret=read(events[i].data.fd,buf,BUFSIZE);
                    if(read_ret==-1)
                    {
                        perror("read error");
                        exit(1);
                    }
                    else if(read_ret==0)
                    {
                        printf("客户端退出\n");
                        close(events[i].data.fd);
                        epoll_ctl(epfd,EPOLL_CTL_DEL,events[i].data.fd,NULL);
                    }
                    else
                    {
                        write(events[i].data.fd,buf,read_ret);
                        printf("*****************\n");
                        write(STDOUT_FILENO,buf,read_ret);
                        printf("*****************\n");
                    }
                }
            }
        }
    }
    return 0;
}


